package com.x.ant.service;

import com.x.ant.dao.TruckDao;
import com.x.ant.manage.TruckManage;
import com.x.ant.model.Truck;
import com.x.framework.exception.BusinessException;
import com.x.framework.exception.ExceptionCode;
import com.x.framework.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class TruckService extends BaseService {
    @Autowired
    private TruckManage truckManage;

    @Autowired
    private TruckDao truckDao;

    private static Map<String, List<Truck>> truckListMap = new HashMap<String, List<Truck>>();
    private static Truck t = new Truck();

    public List<Truck> searchTruckList(String deptParentId, String truckPlateCode) {
        List<Truck> truckList = truckListMap.get(deptParentId);
        if(truckList == null) {
            truckList = this.selectTruckList(t, deptParentId);
            truckListMap.put(deptParentId, truckList);
        }
        List<Truck> list = new ArrayList<Truck>(10);
        int index = 0;
        for(Truck truck : truckList) {
            if(truck.getTruckPlateCode().startsWith(truckPlateCode)) {
                list.add(truck);
                index++;
                if(index == 10) {
                    break;
                }
            }
        }
        return list;
    }

    public List<Truck> selectTruckList(Truck truck, String deptParentId) {
        try {
            return truckDao.selectTruckList(truck, deptParentId);
        } catch (Exception e){
            throw new BusinessException(ExceptionCode.EXCEPTION_CODE0000, e);
        }
    }

    public int selectTruckNum(Truck truck, String deptParentId) {
        try {
            return truckDao.selectTruckNum(truck, deptParentId);
        } catch (Exception e){
            throw new BusinessException(ExceptionCode.EXCEPTION_CODE0000, e);
        }
    }

    public Truck insertTruck(Truck truck, String deptId, String deptParentId) {
        try {
            truckListMap.remove(deptParentId);
            return truckManage.insertTruck(truck, deptId, deptParentId);
        } catch (Exception e){
            throw new BusinessException(ExceptionCode.EXCEPTION_CODE0000, e);
        }
    }

}
